package com.xiao.blecontrol;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.*;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.*;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    //页面元素相关变量
    private SeekBar seekBarKk1;
    private SeekBar seekBarKk2;
    private Button connect;
    private Button barKk1Sub;
    private Button barKk2Sub;
    private Button barKk1Plus;
    private Button barKk2Plus;
    private Button confirm;
    private Button cancle;
    private Button search;
    private EditText connectEditText;
    private TextView modelTextView;
    private TextView timeTextView;
    private TextView currentView;

    private RecyclerView rvDeviceList;
    private static final int REQUEST_CODE_ACCESS_COARSE_LOCATION = 1;

    private Boolean isWrite = false;

    //是否验证通过 1表示验证通过，0表示未通过
    private Integer state = 0;
    //蓝牙相关变量
    private BluetoothManager mBluetoothManager;
    private BluetoothAdapter mBluetoothAdapter;
    private final int REQUEST_ENABLE_BT = 1;
    private BleService mBleService;
    private BleReceiver mBleReceiver;
    private List<BluetoothDevice> mBluetoothDeviceList;
    private List<String> mRssiList;
    private DeviceListAdapter mDeviceListAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        connect = findViewById(R.id.connect);
        connectEditText = findViewById(R.id.connect_edit_text);
        modelTextView = findViewById(R.id.model_value);
        timeTextView = findViewById(R.id.time_value);
        seekBarKk1 = findViewById(R.id.bar_kk1);
        barKk1Sub = findViewById(R.id.bar_kk1_sub);
        barKk1Plus = findViewById(R.id.bar_kk1_plus);
        barKk2Sub = findViewById(R.id.bar_kk2_sub);
        barKk2Plus = findViewById(R.id.bar_kk2_plus);
        seekBarKk2 = findViewById(R.id.bar_kk2);
        confirm = findViewById(R.id.confirm);
        cancle = findViewById(R.id.cancle);
        currentView = findViewById(R.id.current_value);
        search = findViewById(R.id.search);

        rvDeviceList = (RecyclerView) findViewById(R.id.rv_device_list);
        //设置按钮点击事件监听
        connect.setOnClickListener(this);
        barKk1Sub.setOnClickListener(this);
        barKk1Plus.setOnClickListener(this);
        barKk2Sub.setOnClickListener(this);
        barKk2Plus.setOnClickListener(this);
        confirm.setOnClickListener(this);
        cancle.setOnClickListener(this);
        search.setOnClickListener(this);


        SeekBar.OnSeekBarChangeListener scl1 = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                progress = progress+80;
                modelTextView.setText(String.valueOf((float) progress / 100));

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        seekBarKk1.setOnSeekBarChangeListener(scl1);
        SeekBar.OnSeekBarChangeListener scl2 = new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                timeTextView.setText(String.valueOf(progress));
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        };
        seekBarKk2.setOnSeekBarChangeListener(scl2);
        //初始化蓝牙
        initBle();
        initData();
        registerBleReceiver();
        local();

        //连接按钮
    }
    /**
     * 初始化蓝牙
     */
    private void initBle() {
        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        if (mBluetoothManager == null) {
            Toast.makeText(this, "蓝牙不可用", Toast.LENGTH_LONG).show();
            return;
        }
        mBluetoothAdapter = mBluetoothManager.getAdapter();
        if (!mBluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, REQUEST_ENABLE_BT);
            return;
        }

        // 搜索蓝牙设备
        scanBleDevice();
        //直接连接
    }
    /**
     * 初始化数据
     */
    private void initData() {
        Log.i("main","我进来了");
        // 蓝牙设备列表
        mBluetoothDeviceList = new ArrayList<>();
        // 蓝牙设备RSSI列表
        mRssiList = new ArrayList<>();
        mDeviceListAdapter = new DeviceListAdapter(mBluetoothDeviceList, mRssiList);
        rvDeviceList.setLayoutManager(new LinearLayoutManager(this));
        rvDeviceList.setAdapter(mDeviceListAdapter);

        // 连接蓝牙设备
        mDeviceListAdapter.setOnItemClickListener(new DeviceListAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                Toast.makeText(MainActivity.this, "开始连接", Toast.LENGTH_SHORT).show();
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
                mBleService.connect(mBluetoothAdapter, mBluetoothDeviceList.get(position).getAddress());
            }
        });
    }
    /**
     * 搜索蓝牙设备
     */
    private void scanBleDevice() {
        mBluetoothAdapter.stopLeScan(mLeScanCallback);
        mBluetoothAdapter.startLeScan(mLeScanCallback);
        // 搜索10s
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mBluetoothAdapter.stopLeScan(mLeScanCallback);
            }
        }, 10000);
    }

    /**
     * 搜索蓝牙设备回调
     */
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {
            if (!mBluetoothDeviceList.contains(bluetoothDevice)) {
                mBluetoothDeviceList.add(bluetoothDevice);
                mRssiList.add(String.valueOf(i));
                mDeviceListAdapter.notifyDataSetChanged();
            }
        }
    };

    /**
     * 注册蓝牙信息接收器
     */
    private void registerBleReceiver() {
        // 绑定服务
        Intent intent = new Intent(this, BleService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
        startService(intent);

        // 注册蓝牙信息广播接收器
        IntentFilter filter = new IntentFilter();
        filter.addAction(BleService.ACTION_GATT_CONNECTED);
        filter.addAction(BleService.ACTION_GATT_DISCONNECTED);
        filter.addAction(BleService.ACTION_GATT_SERVICES_DISCOVERED);
        filter.addAction(BleService.ACTION_DATA_AVAILABLE);
        filter.addAction(BleService.ACTION_CONNECTING_FAIL);
        mBleReceiver = new BleReceiver();
        registerReceiver(mBleReceiver, filter);
    }
    /**
     * 服务
     */
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder rawBinder) {
            mBleService = ((BleService.LocalBinder) rawBinder).getService();
        }

        public void onServiceDisconnected(ComponentName classname) {
            mBleService = null;
        }
    };
    /**
     * 蓝牙信息接收器
     */
    private class BleReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            switch (action) {
                case BleService.ACTION_GATT_CONNECTED:
                    Toast.makeText(MainActivity.this, "蓝牙已连接", Toast.LENGTH_SHORT).show();
                    break;

                case BleService.ACTION_GATT_DISCONNECTED:
                    Toast.makeText(MainActivity.this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
                    mBleService.release();
                    break;

                case BleService.ACTION_GATT_SERVICES_DISCOVERED:
                    Toast.makeText(MainActivity.this, "发现服务了", Toast.LENGTH_SHORT).show();
                    mBleService.setBleNotification();
                    break;

                case BleService.ACTION_CONNECTING_FAIL:
                    Toast.makeText(MainActivity.this, "蓝牙已断开", Toast.LENGTH_SHORT).show();
                    mBleService.disconnect();
                    break;

                case BleService.ACTION_DATA_AVAILABLE:
                    byte[] data = intent.getByteArrayExtra(BleService.EXTRA_DATA);
                    try {
                        String text = ByteUtils.byteArrayToHexString(data);
                        //Toast.makeText(MainActivity.this, "收到数据："+text, Toast.LENGTH_SHORT).show();
                        String controlStr =  ByteUtils.getControlStr(text);
                        switch (controlStr){
                            case "14":
                                float  value = (float) Integer.valueOf( ByteUtils.getValue(text),16)/100;
                                String valueStr = value+"V";
                                if(!isWrite) {
                                    //显示模式值
                                    float modelValue = ((float) Integer.valueOf(ByteUtils.getModelValue(text), 16)) / 100;
                                    //Toast.makeText(MainActivity.this, "模式值："+modelValue, Toast.LENGTH_SHORT).show();
                                    modelTextView.setText(String.valueOf(modelValue));
                                    seekBarKk1.setProgress(Integer.valueOf(ByteUtils.getModelValue(text), 16)- 80);
                                    //显示time值
                                    float timeValue = Integer.valueOf(ByteUtils.getTimeValue(text), 16);
                                    //Toast.makeText(MainActivity.this, "时间值："+timeValue, Toast.LENGTH_SHORT).show();
                                    timeTextView.setText(String.valueOf(timeValue));
                                    seekBarKk2.setProgress((int) timeValue);
                                    isWrite = true;
                                }
                                currentView.setText(valueStr);
                                break;
                            case "11":
                                state = 1;
                                Toast.makeText(MainActivity.this, "连接成功！", Toast.LENGTH_SHORT).show();
                                connect.setBackgroundColor(Color.parseColor("#228B22"));
                                isWrite = false;
                                break;
                             case "12":
                                 isWrite = false;
                                 Toast.makeText(MainActivity.this, "设置成功！", Toast.LENGTH_SHORT).show();
                                 break;
                        }

                        Log.i("蓝牙", "收到的数据123：" + text);


                    }catch (Exception e){
                        Log.i("蓝牙",e.getMessage());
                    }
                    break;

                default:
                    break;
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_ENABLE_BT:
                // 直接连接蓝牙设备
                scanBleDevice();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBleReceiver != null) {
            unregisterReceiver(mBleReceiver);
            mBleReceiver = null;
        }
        unbindService(mServiceConnection);
        mBleService = null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.bar_kk1_sub:
                Log.i("this","点击-了！");
                // seekBarKk1.set
                SeekBarUtil.sub(seekBarKk1,1,80,modelTextView,1);
                break;
            case R.id.bar_kk1_plus:
               Log.i("this","点击+了！");
               SeekBarUtil.plus(seekBarKk1,1,modelTextView,1);
               break;
            case R.id.bar_kk2_sub:
                Log.i("this","点击-了！");
                SeekBarUtil.sub(seekBarKk2,1,0,timeTextView,2);
                break;
            case R.id.bar_kk2_plus:
                Log.i("this","点击+了！");
                SeekBarUtil.plus(seekBarKk2,1,timeTextView,2);
                break;
            case R.id.connect:
                String connectStr = connectEditText.getText().toString();
                Log.i("mian", "输入串：" + connectStr);
                if(TextUtils.isEmpty(connectStr)){
                    Toast.makeText(MainActivity.this, "密码不能为空！", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(!"20190905".equals(connectStr)){
                    Toast.makeText(MainActivity.this, "密码不正确！", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    byte[] sendData = ByteUtils.packageSendData(1,0,0,0,0);
                    //System.out.println(ByteUtils.byteArrayToHexString(ByteUtils.packageSendData(1,0,0,0,0)));
                   //Log.i("mian", "加密数据123：" +  ByteUtils.getString(ByteUtils.getChars("ST12345678\r\n".getBytes("UTF-16"))));
//                    Log.i("main","解密数据："+ByteUtils.decryp("01",passwordData));
                    mBleService.sendData(sendData);
                    isWrite = false;


                }catch (Exception e){
                    //System.out.println(e.getMessage());
                }

                break;
            case R.id.confirm:
                try {
                    if(0==state){
                        Toast.makeText(MainActivity.this, "请输入密码连接！", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    int modelValue = seekBarKk1.getProgress()+80;
                    int timeValue = seekBarKk2.getProgress();
                    byte[] setData = ByteUtils.packageSendData(2,modelValue,0,timeValue,0);

                    //System.out.println(ByteUtils.byteArrayToHexString(setData));
                    mBleService.sendData(setData);
                    isWrite = false;
                }catch (Exception e){
                    Log.i("main",e.getMessage());
                }
                break;
            case R.id.cancle:
                seekBarKk1.setProgress(20);
                seekBarKk2.setProgress(0);
                modelTextView.setText("1");
                timeTextView.setText("0");
                isWrite = false;
                break;
            case R.id.search:
                // 搜索蓝牙设备
                scanBleDevice();
                // 初始化数据
                initData();
                // 注册蓝牙信息接收器
                registerBleReceiver();
                break;

        }

    }
    public void local(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//如果 API level 是大于等于 23(Android 6.0) 时
            //判断是否具有权限
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                //判断是否需要向用户解释为什么需要申请该权限
                if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                        Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    Toast.makeText(MainActivity.this,"需要打开位置权限才可以搜索到Ble设备", Toast.LENGTH_SHORT).show();
                }
                //请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                        REQUEST_CODE_ACCESS_COARSE_LOCATION);
            }
        }
    }
}
